package com.ztjava.core.tool;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import sun.misc.BASE64Decoder;

import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.upload.UploadFile;
import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.io.IoUtil;
import com.ztjava.core.Constant;
import com.ztjava.core.Jsub;

@SuppressWarnings("restriction")
public class UploadTool {

	/***
	 * base64转图片
	 * @param files
	 * @param filepath
	 */
	public static void base64ToImg(String files,String filepath){
		BASE64Decoder decoder = new BASE64Decoder();  
		try{  
			if(files.indexOf(";")>-1){
		        files = files.split(";")[1];
		        files = files.substring(7,files.length());
			}
			byte[] b = decoder.decodeBuffer(files);  
	        for(int i=0;i<b.length;++i){  
	        	if(b[i]<0)  {
	        		b[i]+=256;  
	             }  
	        }
	        OutputStream out = new FileOutputStream(filepath);      
	        out.write(b);  
	        out.flush();  
	        out.close();  
		}catch (Exception e) {
			e.printStackTrace();
		} 
	}
	/***
	 * 获取扩展名，带.号
	 * @param filename
	 * @return
	 */
	public static String getFileExt(String filename){
		String ext = "";
		if (filename.lastIndexOf(".") > -1) {
			ext = filename.substring(filename.lastIndexOf("."),filename.length()).toLowerCase();
		}
		return ext;
	}
	
	
	/**
	 * 根据getContentType 选择上传方式
	 * @param controller
	 * @param user_id
	 * @return
	 */
	public static Ret upload(Controller controller,Integer user_id){
		if ("application/octet-stream".equals(controller.getRequest().getContentType())) {
			return html5Upload(controller,user_id);
		}else {
			return normalUpload(controller,user_id);
		}
	}
	public static Ret normalUpload(Controller controller,Integer user_id){
		if(user_id==null) user_id = 0;
		UploadFile file = controller.getFile();
		if(file==null) Ret.create(Constant.RESULT,Constant.ERROR).set(Constant.MESSAGE, "文件不存在！");	
		return normalUpload(file, controller.getPara("directory", "other"), user_id);
	}
	/***
	 * 普通文件上传
	 * @param file
	 * @param directory
	 * @param user_id
	 * @return
	 */
	public static Ret normalUpload(UploadFile file,String directory,Integer user_id){
		if(user_id==null) user_id = 0;
		Ret ret = new Ret();
		try {
			if(file==null) return Ret.create(Constant.RESULT,Constant.ERROR).set(Constant.MESSAGE, "文件不存在！");	
			
			ret.set("size", file.getFile().length()/1024);
			String ext = getFileExt(file.getFileName());
			String filePath =  getFilePath(Jsub.upload_path, Jsub.folder
					, directory, ext, user_id);
			
			file.getFile().renameTo(new File(Jsub.upload_path+filePath)); 
	        ret.set(Constant.RESULT, Constant.SUCCESS);
	        ret.set(Constant.MESSAGE, "上传成功！");
	        ret.set("name", file.getFileName());
	        ret.set("parameter", file.getParameterName());
	        ret.set("folerPath", Jsub.upload_path+filePath);
	        ret.set("filePath",filePath.replace(File.separator, "/"));
	        ret.set("ext", ext);
		}catch (Exception e){
			e.printStackTrace();
	        ret.set("name", file.getFileName());
	        ret.set("parameter", file.getParameterName());
	        ret.set(Constant.RESULT, Constant.ERROR);
	        ret.set(Constant.MESSAGE, "上传失败！");
		}
        return ret;
	}
	/***
	 * 远程下载文件
	 * @param url
	 * @param model
	 * @param user_id
	 * @return
	 */
	public static Ret downloadFile(String url,String model,Integer user_id){
		Ret ret = new Ret();		
		BufferedOutputStream out = null;
		InputStream in = null;
		URLConnection conn;
		try {
			conn = new URL(url).openConnection();
	        String filePath =  getFilePath(Jsub.upload_path, Jsub.folder, model, 
					getFileExt(getHtml5UploadFilename(conn.getHeaderField("Content-Disposition"))), user_id);
			in = conn.getInputStream();
			int i = conn.getContentLength(); 
			byte buffer[] = new byte[i];  
	        int j = 0;  
	        while (j < i) { // 获取表单的上传文件  
	            int k = in.read(buffer, j, i - j);  
	            j += k;  
	        }  
	        out = new BufferedOutputStream(new FileOutputStream(Jsub.upload_path+filePath, true)); 
	        out.write(buffer);  
	        out.close(); 
	        ret.set(Constant.RESULT, Constant.SUCCESS);
	        ret.set(Constant.MESSAGE, "上传成功！");
	        ret.set("filePath",filePath.replace(File.separator, "/"));
		}catch(Exception e){
			e.printStackTrace();
	        ret.set(Constant.RESULT, Constant.ERROR);
	        ret.set(Constant.MESSAGE, "获取失败！");
		}finally {
			IoUtil.close(in);
			IoUtil.close(out);
		}
		return ret;
	}
	
	public static Ret html5Upload(Controller controller,Integer user_id) {
		if(user_id==null) user_id = 0;
		Ret ret = new Ret();
		try {
			int i = controller.getRequest().getContentLength();  
			byte buffer[] = new byte[i];  
	        int j = 0;  
	        while (j < i) { // 获取表单的上传文件  
	            int k = controller.getRequest().getInputStream().read(buffer, j, i - j);  
	            j += k;  
	        }  
	        if (buffer.length == 0) { // 文件是否为空  
		        ret.set(Constant.RESULT, Constant.ERROR);
		        ret.set(Constant.MESSAGE, "文件不存在！");
		        return ret;
	        }  
			ret.set("size", buffer.length/1024);
	        String filename = getHtml5UploadFilename(controller.getRequest().getHeader("Content-Disposition"));
	        String ext = getFileExt(filename);
			String filePath =  getFilePath(Jsub.upload_path, Jsub.folder
					, controller.getPara("directory", "other"), ext, user_id);
	        
	        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(Jsub.upload_path+filePath, true));  
	        out.write(buffer);  
	        out.close();  
	        ret.set(Constant.RESULT, Constant.SUCCESS);
	        ret.set(Constant.MESSAGE, "上传成功！");
	        ret.set("name", filename);
	        ret.set("parameter", getHtml5Paramename(controller.getRequest()));
	        ret.set("folerPath", Jsub.upload_path+filePath);
	        ret.set("filePath",filePath.replace(File.separator, "/"));
	        ret.set("ext", ext);
		}catch(Exception e) {
			e.printStackTrace();
	        ret.set("name", getHtml5UploadFilename(controller.getRequest().getHeader("Content-Disposition")));
	        ret.set("parameter", getHtml5Paramename(controller.getRequest()));
	        ret.set(Constant.RESULT, Constant.ERROR);
	        ret.set(Constant.MESSAGE, "上传失败！");
		}
        return ret;
	}
	/***
	 * html5获取文件名称
	 * @param request
	 * @return
	 */
	public static String getHtml5UploadFilename(String dispoString){
		int iFindStart = dispoString.indexOf("name=\"") + 6;  
		int iFindEnd = dispoString.indexOf("\"", iFindStart);  
		iFindStart = dispoString.indexOf("filename=\"") + 10;  
		iFindEnd = dispoString.indexOf("\"", iFindStart);  
		return dispoString.substring(iFindStart, iFindEnd);  
	}
	/***
	 * html5获取参数名称
	 * @param request
	 * @return
	 */
	public static String getHtml5Paramename(HttpServletRequest request){
		String dispoString = request.getHeader("Content-Disposition");  
		int iFindStart = dispoString.indexOf("name=\"") + 6;  
		int iFindEnd = dispoString.indexOf("\"", iFindStart);  
		return dispoString.substring(iFindStart, iFindEnd);  
	}

	/***
	 * 获取文件夹
	 * @param server_upload_path
	 * @param app_upload_path
	 * @param model_path
	 * @param user_id
	 * @return
	 */
	public static String getFileDir(String app_upload_path,String model_path,Integer user_id){
		StringBuffer folderPath = new StringBuffer();
		folderPath.append(File.separator);
		folderPath.append("uploadfiles");
		folderPath.append(File.separator);
		folderPath.append(app_upload_path);
		folderPath.append(File.separator);
		folderPath.append(model_path);
		folderPath.append(File.separator);
		folderPath.append(DateUtil.format( new Date(),"yyyyMM"));
		folderPath.append(File.separator);
		folderPath.append(user_id);
		folderPath.append(File.separator);
        return folderPath.toString();
	}
	/***
	 * 获取文件路径
	 * @param server_upload_path
	 * @param app_upload_path
	 * @param model_path
	 * @param ext
	 * @param user_id
	 * @return
	 */
	public static String getFilePath(String server_upload_path,String app_upload_path
			,String model_path,String ext,Integer user_id){
		String fileDir = getFileDir(app_upload_path, model_path, user_id);
        File dir = new File(server_upload_path+fileDir); // 构建文件目录以及目录文件  
        if (!dir.exists()) dir.mkdirs();
		return fileDir +DateUtil.format(new Date(), "yyyyMMddHHmmss") +(new Random().nextInt(89999)+10000)+ext;
	}
	
    public static void downloadUrl(String destUrl,String filePath) {    
        FileOutputStream fos = null;    
        BufferedInputStream bis = null;    
        HttpURLConnection httpUrl = null;    
        URL url = null;    
        int BUFFER_SIZE = 1024;    
        byte[] buf = new byte[BUFFER_SIZE];    
        int size = 0;    
        try {    
            url = new URL(destUrl);    
            httpUrl = (HttpURLConnection) url.openConnection();    
            httpUrl.connect();    
            bis = new BufferedInputStream(httpUrl.getInputStream());    
            fos = new FileOutputStream(filePath);    
            while ((size = bis.read(buf)) != -1) {     
                fos.write(buf, 0, size);    
            }    
            fos.flush();    
        } catch (IOException e) {    
        } catch (ClassCastException e) {    
        } finally {    
            try {    
                fos.close();    
                bis.close();    
                httpUrl.disconnect();    
            } catch (IOException e) {    
            } catch (NullPointerException e) {    
            }    
        }    
    }   
}
